package com.openflag.bwicservice.service.impl;

import com.openflag.bwicservice.domain.Bwic;
import com.openflag.bwicservice.domain.Client;
import com.openflag.bwicservice.domain.Result;
import com.openflag.bwicservice.domain.ValueBondsRequest;
import com.openflag.bwicservice.repository.BwicRepository;
import com.openflag.bwicservice.service.TraderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import static com.openflag.bwicservice.domain.ResultStatus.*;
import static com.openflag.bwicservice.util.ResultUtil.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class TraderServiceImpl implements TraderService {


    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private BwicRepository bwicRepository;

    @Override
    public Result<List<Bwic>> traderUnvaluedList(Long clientId){

        Integer position = restTemplate.getForObject("http://localhost:8087/position/{id}",Integer.class,clientId);
        if (position!=0){
            return fail(USER_NOT_TRADER);
        }

        List<Bwic> bwicList = bwicRepository.getUnvaluedList();

        Result<List<Bwic>> result = success(bwicList);


        return result;


    }

    @Override
    public Result<List<Bwic>> traderValueBonds(ValueBondsRequest valueBondsRequest){
        Long clientId = valueBondsRequest.getClientId();
        Integer position = restTemplate.getForObject("http://localhost:8087/position/{id}",Integer.class,clientId);
        if (position!=0){
            return fail(USER_NOT_TRADER);
        }
        Long marketValue = valueBondsRequest.getMarketValue();
        if(marketValue<0){
            return fail(USER_MARKETVALUE_LOWWER_ZERO);
        }
        Bwic queryBwic = new Bwic();
        queryBwic.setId(valueBondsRequest.getBwicId());

        Optional<Bwic> optionalBwic = bwicRepository.findOne(Example.of(queryBwic));



        if (!optionalBwic.isPresent()){
            return fail(BWIC_NOT_EXIST);
        }




        optionalBwic.get().setMarketValue(valueBondsRequest.getMarketValue());
        optionalBwic.get().setStatus(1);

        bwicRepository.save(optionalBwic.get());


        return success(bwicRepository.getUnvaluedList());


    }
}
